import React, { Component } from "react";
import styles from "./index.module.css";
//import axios from "axios";
import Pubsub from "pubsub-js";
export default class Search extends Component {
  iptRef = React.createRef();
  handleSearch = async () => {
    const { value: keyword } = this.iptRef.current;
    Pubsub.publish("updateListState", {
      isFirstLoad: false,
      loading: true,
      list: []
    });
    // 方法一：axios
    // axios
    //   .get(`/api1/search/users?q=${keyword}`)
    //   .then(res => {
    //     const list = res.data.items;
    //     Pubsub.publish("updateListState", { list });
    //   })
    //   .catch(error => {
    //     Pubsub.publish("updateListState", { err: error.message });
    //     console.error(error);
    //   })
    //   .finally(() => {
    //     Pubsub.publish("updateListState", { loading: false });
    //   });
    // 方法二：fetch
    // fetch(`/api1/search/users2?q=${keyword}`, {
    //   method: "get"
    // })
    //   .then(response => {
    //     return response.json();
    //   })
    //   .then(res => {
    //     const list = res.items;
    //     Pubsub.publish("updateListState", { list });
    //   })
    //   .finally(() => {
    //     Pubsub.publish("updateListState", { loading: false });
    //   });
    // 方法三：async+await+fetch
    try {
      const response = await fetch(`/api1/search/users2?q=${keyword}`);
      const data = await response.json();
      Pubsub.publish("updateListState", { loading: false, list: data.items });
    } catch (error) {
      Pubsub.publish("updateListState", { loading: false, err: error.message });
      console.log("出错了", error);
    }
  };
  render() {
    return (
      <div className={styles.search}>
        <input
          ref={this.iptRef}
          className={styles["search-ipt"]}
          type="text"
          placeholder="输入名字搜索gitHub用户"
        />
        <button className={styles["search-btn"]} onClick={this.handleSearch}>
          搜索
        </button>
      </div>
    );
  }
}
